package com.wlps.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wlps.result.ResultUtils;
import com.wlps.result.ResultVo;
import com.wlps.service.ISysUserService;
import com.wlps.vo.ImageVo;
import com.wlps.vo.LoginVo;
import com.wlps.vo.MenuVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author ZWYZY
 * @since 2020/8/1
 */
@RestController
@Api(tags = "认证", description = "")
@Slf4j
public class CertificationController {
    @Autowired
    private ISysUserService userService;
    public static final String SESSION_KEY = "IMAGE_CODE";
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/api/user/login")
    public ResultVo<MenuVo> login(@RequestAttribute LoginVo loginVo) {
        return ResultUtils.success();
    }

    @PostMapping("/api/user/loginOut")
    public ResultVo loginOut() {
        return ResultUtils.success();
    }

    /**
     * 获取图形验证码
     */
    @GetMapping("/api/user/image")
    public ImageVo imageCode(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
//设置以图片的形式响应
        response.setHeader("Cache-Control", "no-store, no-cache");
//设置页面缓存方式 不缓存，不存储
        response.setContentType("image/jpeg");
// 1. 获取验证码字符串
        String code = defaultKaptcha.createText();
        log.info("生成的图形验证码是：" + code);
// 2. 字符串把它放到session中
        request.getSession().setAttribute(SESSION_KEY, code);
// 3. 获取验证码图片
        BufferedImage image = defaultKaptcha.createImage(code);
// 4. 将验证码图片把它写出去
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        if (out != null) {
            out.close();
        }
        return null;
//        ImageVo imageVo = new ImageVo();
//        imageVo.setImg("http://dummyimage.com/200 x 100/de79f2/fff.png&text=pcordtyu");
//
//        return imageVo;
    }
}
